﻿package gov.jslt.app.plugin.location;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;

public class Location extends CordovaPlugin {

	private LocationClient mLocationClient;
	private CallbackContext callbackContext = null;
	private JSONArray args = null;
	public boolean result = false;
	private JSONObject returnInfo;
	private JSONObject dataObject;

	public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
		if ("getLocationInfo".equals(action)) {
			return getLocationInfo(action, args, callbackContext);
		}
		return false;
	}

	@Override
	public void onDestroy() {
		if (mLocationClient != null && mLocationClient.isStarted()) {
			mLocationClient.stop();
			mLocationClient = null;
		}
		super.onDestroy();
	}

	public boolean getLocationInfo(String action, JSONArray args, CallbackContext callbackContext)
			throws JSONException {
		try {
			this.callbackContext = callbackContext;
			this.args = args;
			cordova.getActivity().runOnUiThread(new Runnable() {
				@Override
				public void run() {
					mLocationClient = new LocationClient(cordova.getActivity());
					try {
						initLocation(Location.this.args);
					} catch (JSONException e) {

					}
					mLocationClient.registerLocationListener(new MyLocationListener());
					mLocationClient.start();
					mLocationClient.requestLocation();
				}

			});
			while (result == false) {
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			return true;

		} catch (Exception e) {
			returnInfo = new JSONObject();
			returnInfo.put("code", "1");
			returnInfo.put("msg", "服务端网络定位失败:" + e.getMessage());
			callbackContext.error(returnInfo);
		}
		return false;
	}

	private void initLocation(JSONArray args) throws JSONException {
		JSONObject param = new JSONObject(args.getJSONObject(0).get("options").toString());
		LocationClientOption option = new LocationClientOption();
		option.setLocationMode(LocationMode.Hight_Accuracy);// 可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
		if (null != param.getString("CoorType") && !"".equals(param.getString("CoorType"))) {
			option.setCoorType(param.getString("CoorType"));
		} else {
			option.setCoorType("bd09ll");// 默认成 百度经纬度标准
		}
		int span = 0;
		option.setScanSpan(span);// 可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
		option.setIsNeedAddress(true);// 可选，设置是否需要地址信息，默认不需要
		option.setOpenGps(true);// 可选，默认false,设置是否使用gps
		option.setLocationNotify(true);// 可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
		option.setIgnoreKillProcess(true);// 可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
		mLocationClient.setLocOption(option);
	}

	/**
	 * 实现实时位置回调监听
	 */
	public class MyLocationListener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			try {
				dataObject = new JSONObject();

				returnInfo = new JSONObject();

				dataObject.put("time", location.getTime());
				dataObject.put("errorCode", location.getLocType());
				dataObject.put("latitude", location.getLatitude());
				dataObject.put("lontitude", location.getLongitude());
				dataObject.put("radius", location.getRadius());
				dataObject.put("locType", location.getLocType());
				if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
					dataObject.put("speed", location.getSpeed());
					dataObject.put("satellite", location.getSatelliteNumber());
					dataObject.put("altitude", location.getAltitude());
					dataObject.put("direction", location.getDirection());
					dataObject.put("addr", location.getAddrStr());
					returnInfo.put("code", "0");
					returnInfo.put("msg", "获取成功");
				} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
					// 网络定位结果
					dataObject.put("operationers", location.getOperators());
					dataObject.put("addr", location.getCity());
					returnInfo.put("code", "0");
					returnInfo.put("msg", "获取成功");
				} else if (location.getLocType() == BDLocation.TypeOffLineLocation) {
					// 离线定位结果
					returnInfo.put("code", "0");
					returnInfo.put("msg", "获取成功");
				} else if (location.getLocType() == BDLocation.TypeServerError) {
					returnInfo.put("code", "1");
					returnInfo.put("msg", "服务端网络定位失败");
				} else if (location.getLocType() == BDLocation.TypeNetWorkException) {
					returnInfo.put("code", "1");
					returnInfo.put("msg", "网络不同导致定位失败，请检查网络是否通畅");
				} else if (location.getLocType() == BDLocation.TypeCriteriaException) {
					returnInfo.put("code", "1");
					returnInfo.put("msg", "无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
				}
				returnInfo.put("data", dataObject);
				callbackContext.success(returnInfo);
				result = true;
			} catch (JSONException e) {

			}
		}

	}

}